<template>
  <div class="community">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="container">
        <div class="row align-items-center">
          <div class="col-md-8">
            <h1 class="page-title">问答社区</h1>
            <p class="page-subtitle">旅行路上的疑问，这里都有答案</p>
          </div>
          <div class="col-md-4 text-md-end">
            <el-button type="primary" size="large" @click="goToAsk">
              <el-icon><QuestionFilled /></el-icon>
              提问
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 社区统计 -->
    <div class="stats-section">
      <div class="container">
        <div class="row text-center">
          <div class="col-md-3 col-6">
            <div class="stat-card">
              <div class="stat-number">{{ stats.questions.toLocaleString() }}</div>
              <div class="stat-label">问题总数</div>
            </div>
          </div>
          <div class="col-md-3 col-6">
            <div class="stat-card">
              <div class="stat-number">{{ stats.answers.toLocaleString() }}</div>
              <div class="stat-label">回答总数</div>
            </div>
          </div>
          <div class="col-md-3 col-6">
            <div class="stat-card">
              <div class="stat-number">{{ stats.users.toLocaleString() }}</div>
              <div class="stat-label">活跃用户</div>
            </div>
          </div>
          <div class="col-md-3 col-6">
            <div class="stat-card">
              <div class="stat-number">{{ stats.solved.toLocaleString() }}</div>
              <div class="stat-label">已解决</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="container">
      <div class="row">
        <!-- 主要内容区域 -->
        <div class="col-lg-8">
          <!-- 筛选标签 -->
          <div class="filter-tabs mb-4">
            <el-tabs v-model="activeTab" @tab-change="handleTabChange">
              <el-tab-pane label="最新" name="latest">
                <template #label>
                  <span><i class="bi bi-clock"></i> 最新</span>
                </template>
              </el-tab-pane>
              <el-tab-pane label="热门" name="hot">
                <template #label>
                  <span><i class="bi bi-fire"></i> 热门</span>
                </template>
              </el-tab-pane>
              <el-tab-pane label="未解决" name="unsolved">
                <template #label>
                  <span><i class="bi bi-question-circle"></i> 未解决</span>
                </template>
              </el-tab-pane>
              <el-tab-pane label="已解决" name="solved">
                <template #label>
                  <span><i class="bi bi-check-circle"></i> 已解决</span>
                </template>
              </el-tab-pane>
            </el-tabs>
          </div>

          <!-- 问题列表 -->
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          
          <div v-else-if="questions.length === 0" class="empty-container">
            <el-empty description="暂无问题">
              <el-button type="primary" @click="goToAsk">提出第一个问题</el-button>
            </el-empty>
          </div>
          
          <div v-else class="questions-list">
            <div
              v-for="question in questions"
              :key="question.id"
              class="question-item"
              @click="goToQuestion(question.id)"
            >
              <div class="question-stats">
                <div class="stat-item">
                  <div class="stat-number">{{ question.answerCount }}</div>
                  <div class="stat-label">回答</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">{{ question.viewCount }}</div>
                  <div class="stat-label">浏览</div>
                </div>
              </div>
              
              <div class="question-content">
                <div class="question-header">
                  <h3 class="question-title">{{ question.title }}</h3>
                  <div class="question-status" v-if="question.isSolved">
                    <el-tag type="success" size="small">已解决</el-tag>
                  </div>
                </div>
                
                <p class="question-summary">{{ truncateText(question.content, 150) }}</p>
                
                <div class="question-tags">
                  <el-tag
                    v-for="tag in question.tags"
                    :key="tag"
                    size="small"
                    effect="plain"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
                
                <div class="question-meta">
                  <div class="author-info">
                    <img :src="question.author.avatar" :alt="question.author.username" class="author-avatar" />
                    <span class="author-name">{{ question.author.username }}</span>
                    <span class="ask-time">提问于 {{ formatDate(question.createTime) }}</span>
                  </div>
                  
                  <div v-if="question.lastAnswer" class="last-answer">
                    <span class="answer-text">最新回答：</span>
                    <img :src="question.lastAnswer.author.avatar" :alt="question.lastAnswer.author.username" class="answer-avatar" />
                    <span class="answer-author">{{ question.lastAnswer.author.username }}</span>
                    <span class="answer-time">{{ formatDate(question.lastAnswer.createTime) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-container" v-if="totalPages > 1">
            <el-pagination
              v-model:current-page="pagination.page"
              :page-size="pagination.pageSize"
              :total="pagination.total"
              layout="prev, pager, next, jumper, total"
              @current-change="handlePageChange"
            />
          </div>
        </div>

        <!-- 侧边栏 -->
        <div class="col-lg-4">
          <div class="sidebar">
            <!-- 搜索框 -->
            <div class="search-card">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索问题..."
                @keyup.enter="handleSearch"
                size="large"
              >
                <template #prepend>
                  <el-icon><Search /></el-icon>
                </template>
                <template #append>
                  <el-button @click="handleSearch">搜索</el-button>
                </template>
              </el-input>
            </div>

            <!-- 热门标签 -->
            <div class="sidebar-card">
              <h4 class="card-title">
                <i class="bi bi-tags"></i> 热门标签
              </h4>
              <div class="hot-tags">
                <el-tag
                  v-for="tag in hotTags"
                  :key="tag.name"
                  @click="searchByTag(tag.name)"
                  class="tag-item"
                  effect="plain"
                >
                  {{ tag.name }} ({{ tag.count }})
                </el-tag>
              </div>
            </div>

            <!-- 活跃用户 -->
            <div class="sidebar-card">
              <h4 class="card-title">
                <i class="bi bi-people"></i> 活跃用户
              </h4>
              <div class="active-users">
                <div
                  v-for="user in activeUsers"
                  :key="user.id"
                  class="user-item"
                >
                  <img :src="user.avatar" :alt="user.username" class="user-avatar" />
                  <div class="user-info">
                    <div class="user-name">{{ user.username }}</div>
                    <div class="user-stats">
                      回答 {{ user.answerCount }} | 采纳 {{ user.acceptedCount }}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 最新回答 -->
            <div class="sidebar-card">
              <h4 class="card-title">
                <i class="bi bi-chat-dots"></i> 最新回答
              </h4>
              <div class="recent-answers">
                <div
                  v-for="answer in recentAnswers"
                  :key="answer.id"
                  class="answer-item"
                  @click="goToQuestion(answer.questionId)"
                >
                  <div class="answer-content">{{ truncateText(answer.content, 80) }}</div>
                  <div class="answer-meta">
                    <span class="answer-author">{{ answer.author.username }}</span>
                    <span class="answer-time">{{ formatDate(answer.createTime) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { defaultAvatar } from '@/assets/images'
import { 
  ElButton, ElTabs, ElTabPane, ElInput, ElIcon, ElTag, 
  ElSkeleton, ElEmpty, ElPagination, ElMessage 
} from 'element-plus'
import { QuestionFilled, Search } from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const questions = ref<any[]>([])
const activeTab = ref('latest')
const searchKeyword = ref('')

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 社区统计
const stats = reactive({
  questions: 15680,
  answers: 42350,
  users: 8920,
  solved: 12450
})

// 热门标签
const hotTags = ref([
  { name: '交通出行', count: 1280 },
  { name: '美食推荐', count: 956 },
  { name: '住宿建议', count: 743 },
  { name: '景点门票', count: 624 },
  { name: '签证办理', count: 512 },
  { name: '行程规划', count: 456 },
  { name: '预算控制', count: 389 },
  { name: '安全提醒', count: 267 }
])

// 活跃用户
const activeUsers = ref([
  {
    id: 1,
    username: '旅行达人小王',
    avatar: defaultAvatar,
    answerCount: 156,
    acceptedCount: 89
  },
  {
    id: 2,
    username: '环球旅行者',
    avatar: defaultAvatar,
    answerCount: 134,
    acceptedCount: 76
  },
  {
    id: 3,
    username: '背包客老李',
    avatar: defaultAvatar,
    answerCount: 98,
    acceptedCount: 52
  }
])

// 最新回答
const recentAnswers = ref([
  {
    id: 1,
    content: '建议提前在网上预订，这样可以节省很多时间，而且价格通常会便宜一些...',
    author: { username: '旅行达人小王' },
    createTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
    questionId: 1
  },
  {
    id: 2,
    content: '从我的经验来看，最好选择靠近地铁站的酒店，出行会非常方便...',
    author: { username: '环球旅行者' },
    createTime: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString(),
    questionId: 2
  }
])

// 计算属性
const totalPages = computed(() => Math.ceil(pagination.total / pagination.pageSize))

// 标签页切换
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
  pagination.page = 1
  loadQuestions()
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadQuestions()
}

// 标签搜索
const searchByTag = (tagName: string) => {
  searchKeyword.value = tagName
  handleSearch()
}

// 页码变化
const handlePageChange = (page: number) => {
  pagination.page = page
  loadQuestions()
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 跳转相关
const goToQuestion = (questionId: number) => {
  router.push({ name: 'PostDetail', params: { id: questionId } })
}

const goToAsk = () => {
  ElMessage.info('提问功能开发中...')
}

// 工具函数
const truncateText = (text: string, length: number) => {
  if (text.length <= length) return text
  return text.substring(0, length) + '...'
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(hours / 24)
  
  if (hours < 1) {
    return '刚刚'
  } else if (hours < 24) {
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}

// 加载问题数据
const loadQuestions = async () => {
  loading.value = true
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 模拟数据
    const mockQuestions = Array.from({ length: pagination.pageSize }, (_, index) => {
      const globalIndex = (pagination.page - 1) * pagination.pageSize + index
      return {
        id: globalIndex + 1,
        title: `关于${hotTags.value[globalIndex % hotTags.value.length].name}的问题 ${globalIndex + 1}`,
        content: '我计划下个月去旅行，想了解一些相关的信息和建议，希望有经验的朋友能够分享一下...',
        answerCount: Math.floor(Math.random() * 20),
        viewCount: Math.floor(Math.random() * 1000),
        isSolved: Math.random() > 0.6,
        tags: hotTags.value.slice(globalIndex % 3, (globalIndex % 3) + 2).map(tag => tag.name),
        author: {
          id: globalIndex + 1,
          username: `用户${globalIndex + 1}`,
          avatar: defaultAvatar
        },
        createTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
        lastAnswer: Math.random() > 0.3 ? {
          author: activeUsers.value[globalIndex % activeUsers.value.length],
          createTime: new Date(Date.now() - Math.random() * 24 * 60 * 60 * 1000).toISOString()
        } : null
      }
    })
    
    questions.value = mockQuestions
    pagination.total = 200 // 模拟总数
  } catch (error) {
    console.error('加载问题失败:', error)
    ElMessage.error('加载问题失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadQuestions()
})
</script>

<style scoped>
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 0;
}

.page-title {
  font-size: 3rem;
  font-weight: 700;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 1.2rem;
  opacity: 0.9;
  margin: 0;
}

.stats-section {
  background: white;
  padding: 30px 0;
  border-bottom: 1px solid #eee;
}

.stat-card {
  padding: 20px;
}

.stat-number {
  font-size: 2rem;
  font-weight: 700;
  color: #667eea;
  margin-bottom: 5px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.filter-tabs {
  background: white;
  border-radius: 10px;
  padding: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.filter-tabs :deep(.el-tabs__header) {
  margin: 0;
}

.filter-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.loading-container,
.empty-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.questions-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.question-item {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  cursor: pointer;
  display: flex;
  gap: 20px;
}

.question-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.question-stats {
  display: flex;
  flex-direction: column;
  gap: 15px;
  min-width: 80px;
}

.stat-item {
  text-align: center;
}

.stat-item .stat-number {
  font-size: 1.2rem;
  font-weight: 600;
  color: #667eea;
  margin: 0;
}

.stat-item .stat-label {
  font-size: 12px;
  color: #999;
  margin: 0;
}

.question-content {
  flex: 1;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.question-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin: 0;
  line-height: 1.4;
}

.question-summary {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.question-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.question-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.author-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.ask-time {
  color: #999;
  font-size: 12px;
}

.last-answer {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #666;
}

.answer-text {
  color: #999;
}

.answer-avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  object-fit: cover;
}

.answer-author {
  color: #667eea;
  font-weight: 500;
}

.answer-time {
  color: #999;
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-card,
.sidebar-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title i {
  color: #667eea;
}

.hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s;
}

.tag-item:hover {
  transform: translateY(-1px);
}

.active-users {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.user-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.user-stats {
  color: #666;
  font-size: 12px;
}

.recent-answers {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.answer-item {
  cursor: pointer;
  padding: 10px;
  border-radius: 8px;
  transition: all 0.3s;
}

.answer-item:hover {
  background: #f5f5f5;
}

.answer-content {
  color: #333;
  font-size: 13px;
  line-height: 1.5;
  margin-bottom: 8px;
}

.answer-meta {
  display: flex;
  justify-content: space-between;
  font-size: 11px;
  color: #999;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .page-header {
    padding: 40px 0;
    text-align: center;
  }
  
  .page-title {
    font-size: 2.2rem;
  }
  
  .question-item {
    flex-direction: column;
    gap: 15px;
  }
  
  .question-stats {
    flex-direction: row;
    justify-content: space-around;
  }
  
  .question-meta {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .sidebar {
    margin-top: 30px;
  }
}
</style>


